package com.shop.shopserver.sender;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.shopcommon.constant.RabbitMQConstant;
import com.shop.shopcommon.context.SecurityContext;
import com.shop.shopcommon.utils.DelayMessageProcessor;
import com.shop.shopcommon.utils.MultiDelayMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.UUID;

@Configuration
public class OrderDelayMessageSender {
    @Autowired
    @Qualifier("rabbitComplexTemplate")
    private RabbitTemplate rabbitComplexTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    public void run(String orderId) throws Exception {
//        Long orderIdLong = Long.parseLong(orderId);
        HashMap<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("userId", String.valueOf(SecurityContext.getUserId()));
        String string = JSON.toJSONString(map);
        MultiDelayMessage msg = MultiDelayMessage.of(string, 4000L, 5000L, 9000L, 10000L);
        System.out.println("msg:" + msg);
        //序列化
        String jsonString = objectMapper.writeValueAsString(msg);
        //发送消息 通过msg.removeNextDelay()返回下一个延迟时间
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
        rabbitComplexTemplate.convertAndSend(RabbitMQConstant.DELAYED_EXCHANGE, RabbitMQConstant.ROUTING_KEY, jsonString, new DelayMessageProcessor(msg.removeNextDelay().intValue()),correlationData);
        System.out.println("发送了:");
    }
}
